package ArrayList

import (
	"errors"
	"fmt"
)

//模拟数组接口
type List interface {
	Size() int                                  //数组大小
	Get(index int) (interface{}, error)         // 返回抓取第几个元素
	Set(index int, newVal interface{}) error    //修改数据
	Insert(index int, newVal interface{}) error //插入数据
	Append(newVal interface{})                  //添加数据
	Clear()                                     // 清空
	Delete(index int) error                     //删除
	String() string                             //输出
	Iterator() Iterator                         //接口
}

//数据结构，字符串，整数，实数
type ArrayList struct {
	dataStore []interface{}
	TheSize   int
}

func NewArrayList() *ArrayList {
	ls := &ArrayList{}
	ls.dataStore = make([]interface{}, 0, 10)
	ls.TheSize = 0
	return ls
}

func (alist *ArrayList) Size() int {
	return alist.TheSize
}

func (alist *ArrayList) Append(newVal interface{}) {
	alist.dataStore = append(alist.dataStore, newVal)
	// fmt.Println(alist.dataStore)
	alist.TheSize++
}

func (alist *ArrayList) String() string {
	return fmt.Sprint(alist.dataStore)
}

//监测内存，如果满了，自动追加
func (alist *ArrayList) checkisFull() {
	if alist.TheSize == cap(alist.dataStore) {
		// fmt.Println("a", alist.dataStore)
		newdataStore := make([]interface{}, 2*alist.TheSize, 2*alist.TheSize) //开辟双倍内存

		copy(newdataStore, alist.dataStore) // 拷贝

		alist.dataStore = newdataStore

		// fmt.Println("A", alist.dataStore)
	}
}

func (alist *ArrayList) Iterator() Iterator {
	it := new(ArrayListIterator)
	/**
	it := ArrayListIterator{
		list:         alist,
		currentIndex: 0,
	}
	*/

	it.list = alist
	it.currentIndex = 0

	return it
}

// 插入数据
func (alist *ArrayList) Insert(index int, newVal interface{}) error {
	if index < 0 && index >= alist.TheSize {
		return errors.New("数组越界")
	}

	alist.checkisFull() //监测内存，如果满了，自动追加

	alist.dataStore = alist.dataStore[:alist.TheSize+1]
	for i := alist.TheSize; i > index; i-- {
		alist.dataStore[i] = alist.dataStore[i-1]
	}
	alist.dataStore[index] = newVal
	alist.TheSize++
	return nil
}

// 清空
func (alist *ArrayList) Clear() {
	alist.dataStore = make([]interface{}, 0, 10)
	alist.TheSize = 0

}

//删除
func (alist *ArrayList) Delete(index int) error {

	if index < 0 && index >= alist.TheSize {
		return errors.New("数组越界")
	}
	alist.dataStore = append(alist.dataStore[:index], alist.dataStore[index+1:]...)
	alist.TheSize--
	return nil
}

// 获取
func (alist *ArrayList) Get(index int) (interface{}, error) {
	if index < 0 && index >= alist.TheSize {
		return nil, errors.New("数组越界")
	}

	return alist.dataStore[index], nil
}

//
func (alist *ArrayList) Set(index int, newVal interface{}) error {
	if index < 0 && index >= alist.TheSize {
		return errors.New("数组越界")
	}
	alist.dataStore[index] = newVal //s设置
	return nil
}
